<template>
  <div class="nav">
    <div class="location" @click="$router.push('/city')">
      {{ $currentCity }} <i class="iconfont ic_site"></i>
    </div>
    <div class="search">
      <i class="iconfont search1" @click="searchCity"></i
      ><input
        type="text"
        placeholder="请输入你所在的城市"
        v-model="city"
        @keyup.enter="searchCity"
      />
    </div>
  </div>
</template>

<script setup>
import { localStorageStoreByCityName } from '@/hooks'
import { useMapCity } from '@/stores/mapCity'
import { ref, toRefs, getCurrentInstance, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { loadArea, getLayerBytitle } from '@/ol-api/index'
const $router = useRouter()
const $useMapCity = useMapCity()
//当前城市
const $currentCity = toRefs($useMapCity).currentCity
//近期访问
const recentCities = ref([])
//输入框中的城市
let city = ref('')
let { proxy } = getCurrentInstance()
let $map = null
//获取当前城市和最近访问
onMounted(async () => {
  $currentCity.value = localStorage.getItem('currentCity') || ''
  $useMapCity.setCurrentCity($currentCity.value)
  recentCities.value = JSON.parse(localStorage.getItem('recentCities')) || []
})
//搜索城市
const searchCity = async () => {
  const layer = getLayerBytitle({ $map })
  $map.removeLayer(layer)
  const $useMapCity = useMapCity()
  $useMapCity.setCurrentCity(city.value)
  //获取区域数据
  await loadArea({ $map })
  city.value = ''
  const cityName = $useMapCity.currentCity
  //对存储的数据进行处理
  localStorageStoreByCityName({ cityName, recentCities })
}

onMounted(async () => {
  //获取当前地图实例
  $map = proxy.$map
  await loadArea({ $map })
})
watch(recentCities, (newval) => {
  localStorage.setItem('recentCities', JSON.stringify(newval))
})
</script>

<style scoped>
.nav {
  width: 100%;
  height: 58px;
  position: fixed;
  top: 0;
  display: flex;
  align-items: center;
  background-color: #4264fb;
  color: #fff;
  z-index: 10;
}
.nav .location {
  width: 88px;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  color: #ffd04b;
  cursor: pointer;
  transition: all 0.3s;
}
.nav .location:hover {
  background-color: #3550c9;
}
.location i {
  color: #ff2d51;
  font-weight: 600;
  font-size: 13px;
}
.nav .search {
  position: relative;
  width: 300px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 20px;
  padding: 1px 11px;
  background-color: #fff;
  border-radius: 4px;
}
.search i {
  width: 30px;
  height: 30px;
  color: #a8abb2;
  font-size: 18px;
  line-height: 30px;
  cursor: pointer;
}
.search input {
  width: 100%;
  height: 100%;
  border: none;
  outline: none;
  background-color: #fff;
  font-size: 14px;
  color: #a8abb2;
  padding-left: 18px;
}
</style>
